package com.maiji.cloud.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.maiji.cloud.entities.shopingmall.*;
import com.maiji.cloud.service.*;
import com.maiji.cloud.service.impl.ShopingOrderServiceImpl;
import com.maiji.cloud.utils.FlowTypeEnum;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class MaijiTask {

    private Logger logger = LoggerFactory.getLogger(ShopingOrderServiceImpl.class);
    @Autowired
    private ShopingOrderService shopingOrderService;
    @Autowired
    private ShopingOrderMiddleShopingCartService somscService;
    @Autowired
    private ShopingCartService shopingCartService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CapitalMainService capitalMainService;
    @Autowired
    private ExchangeLogService exchangeLogService;

    public void TimingCancelOrderTask(String orderId, Long minutes) {
        try {
            ShopingOrder shopingOrder = shopingOrderService.selectById(orderId);
            if (shopingOrder == null || shopingOrder.getStatus() != 0) return;
            shopingOrder.setStatus(4).setCancelReason("自动取消").setCancelDate(new Date());
            String userId = shopingOrder.getUserId();
            if (! shopingOrderService.updateById(shopingOrder))
                logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 失败", new Object[]{minutes, orderId});
            Double fund = shopingOrder.getFund();
            if (fund != null)
                if (! capitalMainService.updateCapitalMain(userId, FlowTypeEnum.FUND, fund.toString(), FlowTypeEnum.INCREASE, FlowTypeEnum.ORDER_CANCEL, orderId))
                    logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 解冻订单使用减肥基金失败 ===>> UserID={} ===>> fund={}元", new Object[]{minutes, orderId, userId, fund});
            Integer integral = shopingOrder.getIntegral();
            if (integral != null)
                if (! capitalMainService.updateCapitalMain(userId, FlowTypeEnum.INTEGRAL, integral.toString(), FlowTypeEnum.INCREASE, FlowTypeEnum.ORDER_REFUND_INTEGRAL, orderId))
                    logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 解冻订单使用积分失败 ===>> UserID={} ===>> integral={}分", new Object[]{minutes, orderId, userId, integral});
            String exchangeId = shopingOrder.getExchangeId();
            if (StringUtil.isNotBlank(exchangeId))
                if (! exchangeLogService.updateById(new ExchangeLog().setUuId(exchangeId).setIsUse(0)))
                    logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 解冻订单使用的优惠券失败 ===>> UserID={} ===>> exchangeId={}", new Object[]{minutes, orderId, userId, exchangeId});
            logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 成功", new Object[]{minutes, orderId});
            List<String> shopingCartIds = somscService.selectList(new EntityWrapper<ShopingOrderMiddleShopingCart>()
                    .eq("order_id", orderId)).parallelStream().map(ShopingOrderMiddleShopingCart::getShopingCartId).collect(Collectors.toList());
            List<ShopingCart> shopingCartList = shopingCartService.selectBatchIds(shopingCartIds);
            List<String> goodsIds = shopingCartList.parallelStream().map(ShopingCart::getGoodsId).collect(Collectors.toList());
            List<Goods> goodsList = goodsService.selectBatchIds(goodsIds);
            Map<String, Integer> scMap = shopingCartList.parallelStream().collect(Collectors.toMap(ShopingCart::getGoodsId, ShopingCart::getPurchaseQuantity));
            goodsList = goodsList.parallelStream().map(goods -> goods.setStockVolume(goods.getStockVolume() + scMap.get(goods.getUuId())).setSalesVolume(goods.getSalesVolume() - scMap.get(goods.getUuId()))).collect(Collectors.toList());
            if (! goodsService.updateBatchById(goodsList))
                logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 修改商品库存和销量失败：goodsIds={}", new Object[]{minutes, orderId, goodsIds});
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("定时{}分钟取消订单 ===>> 订单ID={} ===>> 异常", new Object[]{minutes, orderId});
        }
    }
}

